<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="科目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入科目名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:subject:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="subjectList"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column label="科目编号" align="center" prop="id" />
      <el-table-column label="科目名称" align="center" prop="name" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:subject:edit']"
            >修改</el-button
          >
          <el-button
            type="text"
            icon="Copy"
            @click="handleCopy(scope.row)"
            v-hasPermi="['system:subject:add']"
            >复制</el-button
          >
          <el-button
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:subject:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改科目对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="subjectRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级科目" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="subjectOptions"
            :props="{
              label: 'name',
              value: 'id',
              children: 'children',
              emitPath: false,
            }"
            placeholder="选择上级科目"
            check-strictly
            default-expand-all
          />
        </el-form-item>
        <el-form-item label="科目名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入科目名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  listSubject,
  getSubject,
  delSubject,
  addSubject,
  updateSubject,
  listSubjectTree,
  tree,
} from "@/api/system/subject";
import { ElMessage, ElMessageBox } from "element-plus";

const { proxy } = getCurrentInstance();

const subjectList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");

const queryParams = ref({
  name: undefined,
});

const subjectOptions = ref([]);

const form = ref({
  subjectId: undefined,
  parentId: 0,
  name: undefined,
  weight: 0,
});

const rules = {
  parentId: [{ required: true, message: "上级科目不能为空", trigger: "blur" }],
  name: [{ required: true, message: "科目名称不能为空", trigger: "blur" }],
};

// 添加一个变量保存上次选择的父级ID
const lastSelectedParentId = ref(0);

/** 查询科目列表 */
function getList() {
  loading.value = true;
  tree(queryParams.value).then((response) => {
    subjectList.value = response.data;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    subjectId: undefined,
    parentId: lastSelectedParentId.value, // 使用上次选择的父级ID
    name: undefined,
    weight: 0,
  };
  proxy.resetForm("subjectRef");
  getTreeSelect();
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加科目";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const subjectId = row.subjectId || row.id;
  getSubject(subjectId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改科目";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["subjectRef"].validate((valid) => {
    if (valid) {
      const submitData = {
        id: form.value.subjectId,
        name: form.value.name,
        parentId: form.value.parentId,
        weight: form.value.weight,
      };

      if (form.value.id) {
        submitData.id = form.value.id;
        updateSubject(submitData).then((response) => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSubject(submitData).then((response) => {
          // 保存最后选择的父级ID
          lastSelectedParentId.value = form.value.parentId;
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const subjectId = row.subjectId || row.id;
  ElMessageBox.confirm("是否确认删除该科目?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(function () {
      return delSubject(subjectId);
    })
    .then(() => {
      getList();
      ElMessage.success("删除成功");
    });
}

/** 获取科目树形数据 */
function getTreeSelect() {
  tree().then((response) => {
    subjectOptions.value = [
      {
        id: 0,
        name: "根",
        children: response.data,
      },
    ];
  });
}

/** 复制按钮操作 */
function handleCopy(row) {
  reset();
  open.value = true;
  title.value = "复制科目";
  
  form.value = {
    subjectId: undefined,
    parentId: lastSelectedParentId.value, // 使用上次选择的父级ID
    name: row.name,
    weight: 0
  };
}

onMounted(() => {
  getList();
  getTreeSelect();
});
</script>
